<?php

namespace MoChat\Salesman\Action;

use Hyperf\DbConnection\Db;
use MoChat\App\Call\Constants\ClientTypeCode;
use MoChat\Framework\Action\AbstractAction;
use Hyperf\Di\Annotation\Inject;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\Middleware;
use Hyperf\HttpServer\Annotation\Middlewares;
use Hyperf\HttpServer\Annotation\RequestMapping;
use MoChat\App\Common\Middleware\DashboardAuthMiddleware;
use MoChat\Framework\Request\ValidateSceneTrait;
use MoChat\Framework\Exception\CommonException;
use MoChat\Framework\Constants\ErrorCode;
use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Spreadsheet;

/**
 * 打卡记录
 * @Controller
 */
class ClockInRecordExport extends AbstractAction
{
    use ValidateSceneTrait;

    const TYPE = [
        1 => '门店',
        2 => '诊所',
        3 => '连锁',
        4 => '商业公司',
    ];

    private function timeCheck($data)
    {
        return isset($data['start_time']) && isset($data['end_time']) && !empty($data['start_time']) && !empty($data['end_time']);
    }

    /**
     * @Middlewares({
     *     @Middleware(DashboardAuthMiddleware::class),
     * })
     * @RequestMapping(path="/dashboard/salesman/clockRecordExport", methods="GET")
     */
    public function handle()
    {
        $user = user();
        // 判断用户绑定企业信息
        if (!isset($user['corpIds']) || count($user['corpIds']) !== 1) {
            throw new CommonException(ErrorCode::INVALID_PARAMS, '未选择登录企业，不可操作');
        }
        $data = $this->request->all();
        $list = Db::table('clock_record as record')
            ->join('client as client', 'client.id', '=', 'record.client_id')
            ->join('work_employee as employee', 'employee.id', '=', 'record.work_employee_id')
            ->when(isset($data['name'])&& !empty($data['name']), function ($query) use ($data){
                $query->where('client.enterprise_name','like','%'.$data['name'].'%');
            })
            ->when(isset($data['employee_id'])&& $data['employee_id']!=='', function ($query) use ($data){
                $query->where('employee.id','=',$data['employee_id']);
            })
            ->when(isset($data['employee_id'])&& $data['employee_id']!=='', function ($query) use ($data){
                $query->where('employee.id','=',$data['employee_id']);
            })
            ->when(isset($data['client_id'])&& $data['client_id']!=='', function ($query) use ($data){
                $query->where('client.id','=',$data['client_id']);
            })
            ->when(isset($data['client_name'])&& $data['client_name']!=='', function ($query) use ($data){
                $query->where('client.enterprise_name','like','%'.$data['client_name'].'%');
            })
            ->when($this->timeCheck($data), function ($query) use ($data) {
                $query->where('record.created_at', '>=', $data['start_time']);
                $query->where('record.created_at', '<', $data['end_time']);
            })
            ->when(isset($data['time']) && is_array($data['time']) && $data['time'], function ($query) use ($data) {
                $query->where('record.created_at', '>=', $data['time'][0]);
                $query->where('record.created_at', '<', $data['time'][1].' 23:59:59');
            })
            ->orderBy('record.created_at', 'desc')
            ->select([
                'record.id',
                'client.enterprise_name',//客户名称
                'client.b2b_user_type',//客户类型
                'record.created_at',//签到时间
                'employee.name',//签到人
                'record.address',//签到地址
                'record.lng',//
                'record.lat',//
                'record.image',//图片
                'record.remark'
            ])->get();
        $list || $list = collect([]);
        $list = $list->toArray();
        if (!empty($list)) {
            foreach ($list as &$item) {
                $item->b2b_user_type = self::TYPE[$item->b2b_user_type] ?? '';
            }
            unset($item);
        }
        return $this->processingToTal($list);
    }

    /**
     * 验证规则.
     */
    protected function rules(): array
    {
        return [

        ];
    }

    /**
     * 获取已定义验证规则的错误消息.
     */
    protected function messages(): array
    {
        return [

        ];
    }

    private function processingToTal($tags): array
    {
        $url = '';
        if (!empty($tags)) {
            $newExcel = new Spreadsheet();  //创建一个新的excel文档
            $objSheet = $newExcel->getActiveSheet();  //获取当前操作sheet的对象
            $objSheet->setTitle('签到列表');  //设置当前sheet的标题

            //设置宽度为true,不然太窄了
            $newExcel->getActiveSheet()->getColumnDimension('A')->setAutoSize(true);
            $newExcel->getActiveSheet()->getColumnDimension('B')->setAutoSize(true);
            $newExcel->getActiveSheet()->getColumnDimension('C')->setAutoSize(true);
            $newExcel->getActiveSheet()->getColumnDimension('D')->setAutoSize(true);
            $newExcel->getActiveSheet()->getColumnDimension('E')->setAutoSize(true);
            $newExcel->getActiveSheet()->getColumnDimension('F')->setAutoSize(true);

            //设置第一栏的标题
            $objSheet->setCellValue('A1', '客户名称')
                ->setCellValue('B1', '客户等级')
                ->setCellValue('C1', '签到员工')
                ->setCellValue('D1', '签到时间')
                ->setCellValue('E1', '签到地址')
                ->setCellValue('F1', '签到内容');

            //第二行起，每一行的值,setCellValueExplicit是用来导出文本格式的。
            //->setCellValueExplicit('C' . $k, $val['admin_password']PHPExcel_Cell_DataType::TYPE_STRING),可以用来导出数字不变格式
            foreach ($tags as $k => $tag) {
                $k = $k + 2;
                $objSheet->setCellValue('A' . $k, $tag->enterprise_name)
                    ->setCellValue('B' . $k, $tag->b2b_user_type)
                    ->setCellValue('C' . $k, $tag->name)
                    ->setCellValue('D' . $k, $tag->created_at)
                    ->setCellValue('E' . $k, $tag->address)
                    ->setCellValue('F' . $k, $tag->remark);
            }
            $url = $this->downloadExcel($newExcel, '签到列表', 'Xlsx');
        }
        return ['url' => $url];
    }

    //公共文件，用来传入xls并下载
    public function downloadExcel($newExcel, $filename, $format)
    {
        // $format只能为 Xlsx 或 Xls
        if ($format == 'Xlsx') {
            header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
        } elseif ($format == 'Xls') {
            header('Content-Type: application/vnd.ms-excel');
        }

        header("Content-Disposition: attachment;filename="
            . $filename . date('Y-m-d') . '.' . strtolower($format));
        header('Cache-Control: max-age=0');
        $objWriter = IOFactory::createWriter($newExcel, $format);

//        $objWriter->save('php://output');
        //通过php保存在本地的时候需要用到
        $url = BASE_PATH . '/storage/upload/static' . '/签到列表.xlsx';
        $objWriter->save($url);
        //以下为需要用到IE时候设置
        // If you're serving to IE 9, then the following may be needed
        header('Cache-Control: max-age=1');
        //If you're serving to IE over SSL, then the following may be needed
        header('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
        header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT'); // always modified
        header('Cache-Control: cache, must-revalidate'); // HTTP/1.1
        header('Pragma: public'); // HTTP/1.0
        return env('DASHBOARD_BASE_URL').'/api/static/签到列表.xlsx';
    }

}
